package cgl.sensorgrid.sopac.gps.filters;

import java.util.*;
import cgl.narada.event.*;
import cgl.sensorgrid.filters.*;
import java.io.FileWriter;
import cgl.sensorgrid.common.PropertyFile;
import java.text.SimpleDateFormat;
import java.io.*;

class SaveNetwork {
    public SaveNetwork() {
    }

    private Object syncObj1 = new Object();
    private List eventList = Collections.synchronizedList(new LinkedList());
    private String dataDir;
    private java.util.Properties properties = new java.util.Properties();
    private int noOfObservations;
    static int runcount = 0;

    private Hashtable ht = new Hashtable();

    public SaveNetwork(String[] argsb) {
        loadProperties();
        dataDir = properties.getProperty("gps.data.directory");
        System.out.println(
                "[SaveNetwork] --> Data Directory = " +
                dataDir);
        if (argsb.length == 1) {
            if (argsb[0] != null && argsb[0].length() > 0) {
                this.noOfObservations = Integer.parseInt(argsb[0]);
                System.out.println(
                        "[SaveNetwork] --> # Of Observations per file = " +
                        this.noOfObservations);
            }
        }
    }


    /**
     *
     * @return Properties
     */
    private java.util.Properties loadProperties() {
        // Read properties file.
        try {
            properties = PropertyFile.loadProperties(
                    "sensorgrid.properties");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return properties;
    }


    /**
     *
     * @param event NBEvent
     */
    public void addEvent(NBEvent event) {
        synchronized (syncObj1) {
            eventList.add(event);
            if (eventList.size() == 1) {
                syncObj1.notify();
            }
        }
    }


    /**
     *
     * @param event NBEvent
     */
    public void run() {
        boolean running = true;
        try {
            while (running) {
                synchronized (syncObj1) {
                    if (eventList.size() == 0) {
                        syncObj1.wait();
                    }
                    NBEvent nbEvent = (NBEvent) eventList.remove(0);
                    byte[] data2 = nbEvent.
                                   getContentPayload();
                    if (data2 != null && data2.length > 0) {
                        processMessage(new String(data2));
                    }
                }
            }
            return;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    static int eventcount = 0;

    public void processMessage(String msg) {
        try {
            StringTokenizer st = new StringTokenizer(msg, "\n");
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                if (!token.startsWith("EOF")) {
                    if (token.length() > 4) {
                        String station = token.substring(0, 4);
                        if (ht.get(station) != null) {
                            SaveNetworkMessagesToFiles rd = (SaveNetworkMessagesToFiles) ht.get(station);
                            rd.addLine(token + "\n");
                        } else {
                            SaveNetworkMessagesToFiles rd = new SaveNetworkMessagesToFiles(noOfObservations,
                                    dataDir);
                            rd.setSiteName(station);
                            ht.put(station, rd);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}


/**
 *
 * <p>Title: SensorGrid</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author Galip Aydin
 * @version 1.0
 */
class SaveNetworkMessagesToFiles {
    private String siteName;
    private StringBuffer data;
    private int lineCount;
    private int runcount;
    private int noOfObs;
    private int fwCount;

    private FileWriter fw;
    private String dataDir;
    private String filePath;

    public SaveNetworkMessagesToFiles(int noOfObservations, String dataDir_) {
        this.noOfObs = noOfObservations;
        fwCount = 0;
        siteName = "";
        lineCount = 0;
        data = new StringBuffer();
        dataDir = dataDir_;
        runcount = 0;
    }

    public void setSiteName(String siteName_) {
        this.siteName = siteName_;
        System.out.println(
                "[SaveNetworkMessagesToFiles] ---> Creating DataStruct for " +
                siteName);
        try {
            if (siteName != null && !siteName.equals("")) {
                File f = new File(dataDir + "/" + siteName);
                if(!f.exists()){
                    f.mkdirs();
                }

                this.filePath = dataDir + "/" + siteName + "/" + siteName +
                                "_" +
                                cgl.sensorgrid.common.Tools.getDate(System.currentTimeMillis()) +
                                ".xyz";

                fw = new FileWriter(filePath, true);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void setLineCount(int count) {
        this.setLineCount(count);
    }

    public void increaseLineCount() {
        this.lineCount++;
    }

    public void addLine(String line) {
        try {
            data.append(line);
            increaseLineCount();
            fwCount++;

            if (fwCount >= 25 || this.lineCount >= noOfObs) {
                fw.write(data.toString());
                fw.flush();

                fwCount = 0;
                data = new StringBuffer();
            }

            if (this.lineCount >= noOfObs) {
                fw.flush();
                fw.close();
                runcount++;

                this.filePath = dataDir + "/" + siteName + "/" + siteName + "_" +
                                cgl.sensorgrid.common.Tools.getDate(System.currentTimeMillis()) +
                                ".xyz";

                fw = new FileWriter(filePath, true);
                this.lineCount = 0;
                this.data = new StringBuffer();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public String getSiteName() {
        return siteName;
    }

    public int getLineCount() {
        return this.lineCount;
    }

    public StringBuffer getData() {
        return this.data;
    }

}
/**
 *
 * <p>Title: SensorGrid</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author Galip Aydin
 * @version 1.0
 */
public class SaveNetworkMessages extends Filter {
    public SaveNetworkMessages() {
    }

    private SaveNetwork r2a;

    public SaveNetworkMessages(String[] args, String[] argsb) {
        if (args == null || args.length == 0) {
            System.err.println(
                    "Incorrect number of arguments in ryo2ascii::Constructor...");
        } else {
            this.initialize(args);
            r2a = new SaveNetwork(argsb);
            r2a.run();
        }
    }

    public void onEvent(NBEvent nbEvent) {
        if (nbEvent.getContentPayload() != null) {
            if (r2a != null && nbEvent != null) {
                r2a.addEvent(nbEvent);
            }
        }
    }

    public static void main(String args[]) {
        if (args.length < 5) {
            System.out.println("Usage: java cgl.sensorgrid.sopac.gps.filters.SaveNetwork commType nbHost nbPort subTopic noOfObservations");
            System.exit(0);
        }

        String commType = args[0];
        String nbHost = args[1];
        String nbPort = args[2];
        String subTopic = args[3];
        String noOfObservations = args[4];
//
//        String commType = "tcp";
//        String nbHost = "gf2.ucs.indiana.edu";
//        String nbPort = "5544";
//        String subTopic = "/SOPAC/GPS/CRTN_01/POS";
//        String noOfObservations = "10";

        String[] argsa = {commType,
                         nbHost,
                         nbPort,
                         subTopic,
                         ""};

        String[] argsb = {noOfObservations};
        SaveNetworkMessages test = new SaveNetworkMessages(argsa, argsb);
    }
}


